//
//  ImgViewController.m
//  RoadLine
//
//  Created by dllo on 15/4/21.
//  Copyright (c) 2015年 RedFireNoodles. All rights reserved.
//

#import "ImgViewController.h"
#import "AFHTTPRequestOperationManager.h"
#import "UIImageView+WebCache.h"
#import "ImageDeal.h"
#import "Singleton.h"
#import "TripViewController.h"
#import "PlaceModel.h"
#import "ImageCell.h"
#import "MJRefresh.h"


#define WIDTH self.view.frame.size.width
#define HEIGHT self.view.frame.size.height


@interface ImgViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>

@property(nonatomic, retain)NSMutableArray *dataArr;
// 刷新数据用
@property(nonatomic, assign)NSInteger page;
// 加载动画
@property(nonatomic, retain)UIActivityIndicatorView *activity;
// 控制图片滚动
@property(nonatomic, retain)UICollectionView *collect;
// 瀑布流设置
@property(nonatomic, retain)UICollectionViewFlowLayout *flowLayout;

@property (nonatomic, assign)NSInteger lastIndex;

@end

@implementation ImgViewController

-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.dataArr = [NSMutableArray array];
        self.activity = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];

    }
    return self;

}

// 数据解析
-(void)data{
    // 多线程
    dispatch_queue_t mainQueue = dispatch_get_main_queue();
    dispatch_async(mainQueue, ^{
        
        NSInteger number = self.page * 21;
        NSString *path = [NSString stringWithFormat:@"http://api.breadtrip.com/destination/place/%@/%@/photos/?start=%ld&count=21&gallery_mode=true", self.type, self.pic_id, number];
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        [manager GET:path parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
            
            NSMutableDictionary *dic = responseObject;
            NSMutableArray *arr = [dic objectForKey:@"items"];
            for (NSMutableDictionary *dic in arr) {
                PlaceModel *place = [[PlaceModel alloc] init];
                [place setValuesForKeysWithDictionary:dic];
                [self.dataArr addObject:place];
                [place release];
                
            }
            [self.collect reloadData];
            self.collect.contentOffset = CGPointMake(WIDTH * (self.index - self.page * 21), 0);
            [self.activity stopAnimating];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [self.activity stopAnimating];
        }];
        
    });
   }


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor blackColor];
    // 设置navigationBar 的字体颜色
    UILabel *titleLabelPrice = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 44)];
    titleLabelPrice.font = [UIFont boldSystemFontOfSize:18];
    titleLabelPrice.textColor = [UIColor whiteColor];
    titleLabelPrice.backgroundColor = [UIColor clearColor];
    titleLabelPrice.text = self.title;
    self.navigationItem.titleView = titleLabelPrice;
    [titleLabelPrice release];
 
    // collectionView瀑布流设置
    self.flowLayout = [[UICollectionViewFlowLayout alloc] init];
    self.flowLayout.minimumInteritemSpacing = 0;
    self.flowLayout.minimumLineSpacing = 0;
    self.flowLayout.itemSize = CGSizeMake(WIDTH, HEIGHT);
    // collectionView设置
    self.collect = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - self.navigationController.navigationBar.frame.size.height) collectionViewLayout:self.flowLayout];
    self.collect.delegate = self;
    self.collect.dataSource = self;
    self.collect.pagingEnabled = YES;
    self.flowLayout.scrollDirection=UICollectionViewScrollDirectionHorizontal;
    
    [self.view addSubview:self.collect];
    [self.collect registerClass:[ImageCell class] forCellWithReuseIdentifier:@"reuse"];
    self.collect.backgroundColor = [UIColor colorWithRed:250/255.0 green:245/255.0 blue:232/255.0 alpha:1];
    [self.collect addSubview:self.activity];
    self.activity.center = CGPointMake(WIDTH / 2, HEIGHT / 2);
    [self.activity startAnimating];
    // 设置自定义右Button
    UIButton *rightbutton = [UIButton buttonWithType:UIButtonTypeSystem];
    rightbutton.frame = CGRectMake(0, 0, 70, 30);
    [rightbutton setTitle:@"点击下载" forState:UIControlStateNormal];
    [rightbutton addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:rightbutton] autorelease];
    
    self.page = self.index / 21;
    [self data];
    [_flowLayout release];
    [_collect release];

    if ([Singleton shareSingleton].isNight) {
        [[Singleton shareSingleton] loadNightModeInfoFormDisk];
        
    }
}


// collectionView必须实现的方法
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return self.dataArr.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    // 前一个画面被点击图片的名
//    self.title = [self.dataArr[self.index] trip_name];
    ImageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    PlaceModel *place = self.dataArr[indexPath.row];
    cell.label.text = place.trip_name;
    NSURL *url = [NSURL URLWithString:place.photo_w640];
    cell.label.text = place.text;
    // 实现图片自适应高度
    [cell.myImageView sd_setImageWithURL:url placeholderImage:nil options:SDWebImageRetryFailed progress:^(NSInteger receivedSize, NSInteger expectedSize) {

    } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        CGFloat bili = image.size.height / image.size.width;
        if (image.size.width >= WIDTH) {
            cell.myImageView.frame = CGRectMake(0, 64, WIDTH, WIDTH * bili);
            
        }
    }];

    return cell;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {

    if (self.lastIndex > (NSInteger)(self.collect.contentOffset.x / self.dataArr.count)) {
        self.index--;
    } else if (self.lastIndex < (NSInteger)(self.collect.contentOffset.x / self.dataArr.count)) {
        self.index++;
    } else {
        
    }
    self.lastIndex = self.collect.contentOffset.x / self.dataArr.count;
}

// 将图片下载到本地
- (void)saveImageToPhotos:(UIImage*)image
{
    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error
  contextInfo:(void *)contextInfo
{
    if (error != NULL)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"下载图片失败!" delegate:self cancelButtonTitle:@"确认" otherButtonTitles: nil];
        [alert show];
        [alert release];
    }
    else
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"下载图片成功!" delegate:self cancelButtonTitle:@"确认" otherButtonTitles: nil];
        [alert show];
        [alert release];
    }
}
- (void)setLightDayModel {
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:246/255.0 green:85/255.0 blue:91/255.0 alpha:1];
}

- (void)setNightDayModel {
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:4/255.0 green:165/255.0 blue:171/255.0 alpha:1];
}

// rightButton的点击事件 下载当前图片
- (void)click:(UICollectionView *)collect{
    
    NSInteger idx = self.collect.contentOffset.x /  WIDTH;
    
    UIImageView *imageView = [[UIImageView alloc] init];
    [imageView sd_setImageWithURL:[NSURL URLWithString:[self.dataArr[idx] photo]] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        [self saveImageToPhotos:image];
    }];
    
    
}


-(void)dealloc{

    [_dataArr release];
    [super dealloc];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
